package net.jkdmanager.common.services.messaging;

import java.io.Serializable;
import java.util.List;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;


import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;

@Service("messagingService")
public class MessagingServiceImpl implements MessagingService {

	private static final Log log = LogFactory.getLog(MessagingServiceImpl.class);
	
	@Autowired
	private List<MessageListener> messageListeners;
	
	@Autowired
	private JmsTemplate jmsTemplate;
	
	@Value("${destination.out}")
	private String destination;
	
	public void onMessage(Serializable message) throws JMSException {
		for (MessageListener listener : messageListeners) {
			listener.receiveMessage(message);
		}
	}
		
	public void sendMessage(final Serializable message) {
		try {
			jmsTemplate.send(destination, new MessageCreator() {
				public Message createMessage(Session session) throws JMSException {
					Message response = session.createObjectMessage(message);
					return response ;
				}
			});
		} catch (Exception e) {
			log.error("Problem sending configuration response.", e);
		}

	}

}
